package com.zhugang.week01;

import java.util.Arrays;

/**
 * @program algorithms
 * @description: reverseArray
 * @author: chanzhugang
 * @create: 2022/05/18 23:41
 */
public class ReverseArray {

    public static void main(String[] args) {
        int[] arr = new int[]{1, 2, 3, 4};
        ReverseArray reverseArray = new ReverseArray();
        reverseArray.reverse1(arr, arr.length);
        reverseArray.reverse2(arr, arr.length);
        Arrays.stream(arr).forEach(System.out::println);
    }


    /**
     * 空间复杂度O(n)
     *
     * @param arr
     * @param n
     */
    public void reverse1(int[] arr, int n) {
        int[] temp = new int[n];
        for (int i = 0; i < n; i++) {
            temp[i] = arr[n - i - 1];
        }
        for (int i = 0; i < n; i++) {
            arr[i] = temp[i];
        }
    }

    /**
     * 空间复杂度O(1)
     *
     * @param arr
     * @param n
     */
    public void reverse2(int[] arr, int n) {
        for (int i = 0; i < n / 2; i++) {
            int temp = arr[i];
            arr[i] = arr[n - i - 1];
            arr[n - i - 1] = temp;
        }
    }
}